# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from scrapy.exceptions import DropItem

from example.kaoshi.demo6 import ZBMongoDB


class GuaziPipeline:
    def __init__(self):
        self.mongo = None

    def open_spider(self, spider):
        self.mongo = ZBMongoDB("gz", db="kaoshi")

    def process_item(self, item, spider):
        data = dict(item)
        if isinstance(data, dict):
            self.mongo.insert_one(data)
            return item
        else:
            raise DropItem(f"数据格式错误-{item}")

    def close_spider(self, spider):
        if self.mongo is not None:
            self.mongo.client.close()

